1   /*
2    *   Copyright 2005 Alvaro Gonzalez de Paz
3    *
4    *  Licensed under the Apache License, Version 2.0 (the "License");
5    *  you may not use this file except in compliance with the License.
6    *  You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *  Unless required by applicable law or agreed to in writing, software
11   *  distributed under the License is distributed on an "AS IS" BASIS,
12   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *  See the License for the specific language governing permissions and
14   *  limitations under the License.
15   *  
16   * This is a derived work from source code taken from Liferay.
17   * 	(http://www.liferay.com)
18  */
19  package kortsoft.kmx.test;
20  
21  import java.io.BufferedReader;
22  import java.io.BufferedWriter;
23  import java.io.ByteArrayOutputStream;
24  import java.io.File;
25  import java.io.FileInputStream;
26  import java.io.FileNotFoundException;
27  import java.io.FileOutputStream;
28  import java.io.FileReader;
29  import java.io.FileWriter;
30  import java.io.IOException;
31  import java.io.Reader;
32  
33  import java.nio.channels.FileChannel;
34  
35  import java.util.ArrayList;
36  import java.util.Enumeration;
37  import java.util.List;
38  import java.util.Properties;
39  import java.util.jar.JarEntry;
40  import java.util.jar.JarOutputStream;
41  
42  //import org.apache.commons.lang.StringUtils;
43  
44  /***
45   * File utility methods
46   * @author  Brian Wing Shun Chan, Jorge Ferrer
47   *
48   */
49  public class FileUtil {
50  
51  	public static void copyDirectory(
52  		String sourceDirName, String destinationDirName) {
53  
54  		copyDirectory(new File(sourceDirName), new File(destinationDirName));
55  	}
56  
57  	public static void copyDirectory(File source, File destination) {
58  		if (source.exists() && source.isDirectory()) {
59  			if (!destination.exists()) {
60  				destination.mkdirs();
61  			}
62  
63  			File[] fileArray = source.listFiles();
64  
65  			for (int i = 0; i < fileArray.length; i++) {
66  				if (fileArray[i].isDirectory()) {
67  					copyDirectory(
68  						fileArray[i],
69  						new File(destination.getPath() + File.separator
70  							+ fileArray[i].getName()));
71  				}
72  				else {
73  					copyFile(
74  						fileArray[i],
75  						new File(destination.getPath() + File.separator
76  							+ fileArray[i].getName()));
77  				}
78  			}
79  		}
80  	}
81  
82  	public static void copyFile(
83  		String sourceFileName, String destinationFileName) {
84  
85  		copyFile(new File(sourceFileName), new File(destinationFileName));
86  	}
87  
88  	public static void copyFile(File source, File destination) {
89  		if (!source.exists()) {
90  			return;
91  		}
92  
93  		if ((destination.getParentFile() != null) &&
94  			(!destination.getParentFile().exists())) {
95  
96  			destination.getParentFile().mkdirs();
97  		}
98  
99  		try {
100 			FileChannel srcChannel = new FileInputStream(source).getChannel();
101 			FileChannel dstChannel = new FileOutputStream(
102 				destination).getChannel();
103 
104 			dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
105 
106 			srcChannel.close();
107 			dstChannel.close();
108 		}
109 		catch (IOException ioe) {
110 			ioe.printStackTrace();
111 		}
112 	}
113 
114 	public static void copyFileLazy(String source, String destination)
115 		throws IOException {
116 
117 		String oldContent = null;
118 		try {
119 			oldContent = FileUtil.read(source);
120 		}
121 		catch (FileNotFoundException fnfe) {
122 			return;
123 		}
124 
125 		String newContent = null;
126 		try {
127 			newContent = FileUtil.read(destination);
128 		}
129 		catch (FileNotFoundException fnfe) {
130 		}
131 
132 		if (oldContent == null || !oldContent.equals(newContent)) {
133 			FileUtil.copyFile(source, destination);
134 		}
135 	}
136 
137 	public static void deltree(String directory) {
138 		deltree(new File(directory));
139 	}
140 
141 	public static void deltree(File directory) {
142 		if (directory.exists() && directory.isDirectory()) {
143 			File[] fileArray = directory.listFiles();
144 
145 			for (int i = 0; i < fileArray.length; i++) {
146 				if (fileArray[i].isDirectory()) {
147 					deltree(fileArray[i]);
148 				}
149 				else {
150 					fileArray[i].delete();
151 				}
152 			}
153 
154 			directory.delete();
155 		}
156 	}
157 
158 	public static byte[] getBytes(File file) throws IOException {
159 		if (file == null || !file.exists()) {
160 			return null;
161 		}
162 
163 		ByteArrayOutputStream out = new ByteArrayOutputStream();
164 		FileInputStream in = new FileInputStream(file);
165 
166 		int c = in.read();
167 
168 		while (c != -1) {
169 			out.write(c);
170 			c = in.read();
171 		}
172 
173 		in.close();
174 		out.close();
175 
176 		return out.toByteArray();
177 	}
178 
179 	public static String getPath(String fullFileName) {
180 		int pos = fullFileName.lastIndexOf("/");
181 
182 		if (pos == -1) {
183 			pos = fullFileName.lastIndexOf("//");
184 		}
185 
186 		String shortFileName = fullFileName.substring(0, pos);
187 
188 		if (shortFileName.trim().equals(""))		
189 			return "/";
190 
191 		return shortFileName;
192 	}
193 
194 	public static String getShortFileName(String fullFileName) {
195 		int pos = fullFileName.lastIndexOf("/");
196 
197 		if (pos == -1) {
198 			pos = fullFileName.lastIndexOf("//");
199 		}
200 
201 		String shortFileName =
202 			fullFileName.substring(pos + 1, fullFileName.length());
203 
204 		return shortFileName;
205 	}
206 
207 	public static boolean exists(String fileName) {
208 		File file = new File(fileName);
209 
210 		return file.exists();
211 	}
212 
213 	public static String[] listDirs(String fileName) throws IOException {
214 		return listDirs(new File(fileName));
215 	}
216 
217 	public static String[] listDirs(File file) throws IOException {
218 		List<String> dirs = new ArrayList<String>();
219 
220 		File[] fileArray = file.listFiles();
221 
222 		for (int i = 0; i < fileArray.length; i++) {
223 			if (fileArray[i].isDirectory()) {
224 				dirs.add(fileArray[i].getName());
225 			}
226 		}
227 
228 		return dirs.toArray(new String[0]);
229 	}
230 
231 	public static String[] listFiles(String fileName) throws IOException {
232 		return listFiles(new File(fileName));
233 	}
234 
235 	public static String[] listFiles(File file) throws IOException {
236 		List<String> files = new ArrayList<String>();
237 
238 		File[] fileArray = file.listFiles();
239 
240 		for (int i = 0; i < fileArray.length; i++) {
241 			if (fileArray[i].isFile()) {
242 				files.add(fileArray[i].getName());
243 			}
244 		}
245 
246 		return files.toArray(new String[0]);
247 	}
248 
249 	public static void mkdirs(String pathName) {
250 		File file = new File(pathName);
251 		file.mkdirs();
252 	}
253 
254 	public static boolean move(
255 		String sourceFileName, String destinationFileName) {
256 
257 		return move(new File(sourceFileName), new File(destinationFileName));
258 	}
259 
260 	public static boolean move(File source, File destination) {
261 		if (!source.exists()) {
262 			return false;
263 		}
264 
265 		destination.delete();
266 
267 		return source.renameTo(destination);
268 	}
269 
270 	public static String read(String fileName) throws IOException {
271 		return read(new File(fileName));
272 	}
273 
274 	public static String read(File file) throws IOException {
275 		BufferedReader br = new BufferedReader(new FileReader(file));
276 
277 		StringBuffer sb = new StringBuffer();
278 		String line = null;
279 
280 		while ((line = br.readLine()) != null) {
281 			sb.append(line).append('\n');
282 		}
283 
284 		br.close();
285 
286 		return sb.toString().trim();
287 	}
288 
289 	public static String replaceSeparator(String fileName) {
290 		return fileName.replaceAll("//","/");		
291 	}
292 
293 	public static List toList(Reader reader) {
294 		List<String> list = new ArrayList<String>();
295 
296 		try {
297 			BufferedReader br = new BufferedReader(reader);
298 
299 			StringBuffer sb = new StringBuffer();
300 			String line = null;
301 
302 			while ((line = br.readLine()) != null) {
303 				list.add(line);
304 			}
305 
306 			br.close();
307 		}
308 		catch (IOException ioe) {
309 		}
310 
311 		return list;
312 	}
313 
314 	public static List toList(String fileName) {
315 		try {
316 			return toList(new FileReader(fileName));
317 		}
318 		catch (IOException ioe) {
319 			return new ArrayList();
320 		}
321 	}
322 
323 	public static Properties toProperties(FileInputStream fis) {
324 		Properties props = new Properties();
325 
326 		try {
327 			props.load(fis);
328 		}
329 		catch (IOException ioe) {
330 		}
331 
332 		return props;
333 	}
334 
335 	public static Properties toProperties(String fileName) {
336 		try {
337 			return toProperties(new FileInputStream(fileName));
338 		}
339 		catch (IOException ioe) {
340 			return new Properties();
341 		}
342 	}
343 
344 	public static void write(File file, String s) throws IOException {
345 		if (file.getParent() != null) {
346 			mkdirs(file.getParent());
347 		}
348 
349 		BufferedWriter bw = new BufferedWriter(new FileWriter(file));
350 
351 		bw.flush();
352 		bw.write(s);
353 		bw.flush();
354 
355 		bw.close();
356 	}
357 
358 	public static void write(String fileName, String s) throws IOException {
359 		write(new File(fileName), s);
360 	}
361 
362 	public static void write(String pathName, String fileName, String s)
363 		throws IOException {
364 
365 		write(new File(pathName, fileName), s);
366 	}
367 
368     public static void write(File dest, Properties props) throws IOException {
369         write(dest, propertiesToString(props));             
370     }
371     
372     public static String propertiesToString(Properties p) {
373         StringBuffer sb = new StringBuffer();
374 
375         Enumeration enu = p.propertyNames();
376 
377         while (enu.hasMoreElements()) {
378                 String key = (String)enu.nextElement();
379 
380                 sb.append(key);
381                 sb.append("=");
382                 sb.append(p.getProperty(key));
383                 sb.append("\n");
384         }
385 
386         return sb.toString();
387 }
388 
389     public static void writeAsJAR(File dest, String propsFileName, Properties props) 
390     	throws FileNotFoundException, IOException {
391         JarOutputStream out = new JarOutputStream(new FileOutputStream(dest));
392         JarEntry propertiesFile = new JarEntry(propsFileName);
393         propertiesFile.setExtra(propertiesToString(props).getBytes());
394         out.putNextEntry(propertiesFile);
395         out.close();        
396     }
397 
398 
399 }